package com.aos;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

public class Client extends Thread
{
	public static HashMap<Integer, PrintWriter> senderList = new HashMap<Integer, PrintWriter>();
	
	public void run()
	{
		for(int nodeID : Node.neighbors.keySet())	//for each neighbor create a send socket
		{
			if(nodeID == Node.nodeInfo.getID())
			{
				//the not itself
			}else
			{
				while(true)
				{
					try {
						NodeInfo remoteNode = Node.neighbors.get(nodeID);
						InetAddress remoteAddress = InetAddress.getByName(remoteNode.getAddress());
						
						Socket clienSocket = new Socket(remoteAddress, remoteNode.getPort());
						
						PrintWriter sender = new PrintWriter(clienSocket.getOutputStream(), true);
						senderList.put(nodeID, sender);
						break;
					} catch (IOException e)
					{
						//System.out.println("Exception is here");
						e.printStackTrace();
						//continue;
					}
				}
			}
		}		
		Node.updateNodeState();
		
//		for(Integer neighbor : Node.neighbors.keySet())
//		{
//			Communication.sendMessage(senderList.get(neighbor));
//		}
		
		// Initial flooding started by distinguished node
		if((Node.nodeInfo.getID() == Node.dNode) & (Node.parent == -1)) // the current node is a designated node
		{
			//System.out.println("Distinguished Node Found.");
			while(!Node.isNodeUp())
			{
				
			}
			//System.out.println("Node: \"" + Node.nodeInfo.getID() +"\" ready");
			//System.out.println("Flooding Protocol Initiating...");
			
			Node.parent = Node.dNode;
			for(Integer neighbor : Node.neighbors.keySet())
			{
				// sending 'M' message to all nodes
				Communication.sendMessage(Client.senderList.get(neighbor), Communication.m_msg, Integer.toString(Node.nodeInfo.getID()), Integer.toString(neighbor)); 						
			}									
		}
	}
}
